import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-longest-common-prefix',
  templateUrl: './longest-common-prefix.component.html',
  styleUrls: ['./longest-common-prefix.component.css']
})
export class LongestCommonPrefixComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }


  longestCommonPrefix(strs: string[]): string {

    if (strs[0] === '' || strs.length === 0) return '';

    let result = '';

    for (let i = 0; i < strs[0].length; i++) { // 遍历数组第一项的每个字符
      const current = strs[0][i]; // 用数组第一项每个字符去对比
      for (let j = 0; j < strs.length; j++) // 数组每一项去执行一次
        if (strs[j][i] !== current || !strs[j][i] || strs[j] === '') {
          return result;
        } // 如果两个对比数组项字符串不相同,或者对比目标不存在,或者当前项目此项为空,那么就返回result


      result += current;
    }

    return result;
  }

}
